#!/bin/bash

# OH一点通插件安装脚本
# 用于快速安装和配置OH一点通VSCode插件

set -e

echo "🚀 OH一点通插件安装脚本"
echo "================================"

# 检查Node.js是否安装
if ! command -v node &> /dev/null; then
    echo "❌ 错误: 未找到Node.js，请先安装Node.js"
    echo "请访问 https://nodejs.org/ 下载并安装Node.js"
    exit 1
fi

# 检查npm是否安装
if ! command -v npm &> /dev/null; then
    echo "❌ 错误: 未找到npm，请确保Node.js安装完整"
    exit 1
fi

# 检查VSCode是否安装
if ! command -v code &> /dev/null; then
    echo "❌ 错误: 未找到VSCode命令行工具"
    echo "请确保VSCode已安装，并在VSCode中安装'code'命令"
    echo "按Ctrl+Shift+P，搜索'Shell Command: Install code command in PATH'"
    exit 1
fi

echo "✅ 环境检查通过"

# 进入插件目录
cd "$(dirname "$0")"

echo "📦 安装依赖包..."
npm install

echo "🔨 编译TypeScript代码..."
npm run compile

echo "🔍 检查微服务状态..."
check_service() {
    local service_url=$1
    local service_name=$2
    
    if curl -s --connect-timeout 5 "$service_url" > /dev/null 2>&1; then
        echo "✅ $service_name 运行正常"
        return 0
    else
        echo "⚠️  $service_name 未运行或无法访问"
        return 1
    fi
}

# 检查微服务状态
services_running=0
total_services=6

echo "检查微服务状态..."
check_service "http://localhost:8081/actuator/health" "代码补全服务" && ((services_running++))
check_service "http://localhost:8082/actuator/health" "代码生成服务" && ((services_running++))
check_service "http://localhost:8083/actuator/health" "代码分析服务" && ((services_running++))
check_service "http://localhost:8084/actuator/health" "LLM服务" && ((services_running++))
check_service "http://localhost:8085/actuator/health" "数据服务" && ((services_running++))
check_service "http://localhost:8086/actuator/health" "构建服务" && ((services_running++))

echo "微服务状态: $services_running/$total_services 个服务运行中"

if [ $services_running -eq 0 ]; then
    echo "⚠️  警告: 所有微服务都未运行"
    echo "请确保SmartCodeService微服务集群正在运行"
    echo "可以运行以下命令启动服务:"
    echo "  cd ../ && ./start-all.sh"
fi

echo ""
echo "🎉 OH一点通插件安装完成！"
echo ""
echo "📋 使用说明:"
echo "1. 在VSCode中按F5启动调试模式"
echo "2. 或者运行: code --install-extension oh-yidian-tong-1.0.0.vsix"
echo "3. 在C++文件中按Ctrl+Space进行代码续写"
echo "4. 按Ctrl+Shift+G进行代码生成"
echo "5. 右键菜单选择其他功能"
echo ""
echo "⚙️  配置说明:"
echo "1. 打开VSCode设置 (Ctrl+,)"
echo "2. 搜索'OH一点通'"
echo "3. 配置微服务地址和GLM4.6 API密钥"
echo ""
echo "🔧 故障排除:"
echo "1. 确保微服务正在运行"
echo "2. 检查网络连接"
echo "3. 验证API密钥有效性"
echo "4. 查看VSCode开发者控制台错误信息"
echo ""
echo "📚 更多信息请查看README.md文件"
